导航菜单
首页 >  How to Add Custom JavaScript to Laravel With  > How to Install jQuery in Laravel With Vite

How to Install jQuery in Laravel With Vite

jQuery is a powerful JavaScript library, which simplifies browser scripting and helps make your web application more interactive.

Starting with Laravel 8, Vite has been included as the default build tool. Using Vite to compile your CSS and JS, including dependencies such as jQuery, helps optimize and minify your assets.

In this tutorial, we’ll guide you through the process of installing jQuery using npm, compiling it into your public assets folder, and using the Blade directive @vite to include it in your Blade template. Finally, we’ll demonstrate a simple application of jQuery by changing the color of a paragraph upon clicking.

Let’s get started!

Step 1: Create a New Laravel Project

First, let’s create a new Laravel project if you don’t already have one. Open your terminal and run the following command:

composer create-project laravel/laravel laravel-jquery-vite

Navigate to your project directory:

cd laravel-jquery-viteStep 2: Install jQuery Using npm

In your Laravel project, you can use npm to manage your JavaScript libraries. Let’s install jQuery by running the following command:

npm install jqueryStep 3: Add jQuery import to app.js

Open the resources/js/app.js file and add the following line to import jQuery, right after the standard Laravel bootstrap import:

resources/js/app.jsimport './bootstrap';import jQuery from 'jquery';window.$ = jQuery;Step 4: Install jQuery in Your Blade Templates

Now, let’s include jQuery in your Blade templates. Create a blade file and add the example code shown below:

resources/views/test-jquery.blade.phpgetLocale()) }}">Laracoding.com - Including jQuery with Vite@vite(['resources/css/app.css', 'resources/js/app.js'])

Click me to zoom

" aria-label="Copy">DOCTYPE html>Laracoding.com - Including jQuery with Vite@vite(['resources/css/app.css', 'resources/js/app.js'])Click me to zoom$(document).ready(function(){$(".zoomable").click(function(){$(this).animate({fontSize: "40px"}, 1000);});});

Note that we use the @vite directive to generate the correct URIs to our JS and CSS files in the public folder. Also, note that we use tags on scripts that rely on jQuery being loaded and ready to use. If we don’t load it as a module you will see an error. Read more about why this happens in the FAQ: How to Fix ReferenceError: $ is not defined

Step 5: Add a Route

In your Laravel application, you need a route to render this view. Open routes/web.php and add the following route:

routes/web.php

相关推荐: